// pages/shopCart/shopCart.js
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: app.globalData.imageUrl,
    userInfo: '',
    cartData: '',
    tatalPrice: 0,
    allSelect: false,
    addrId:'',
    isShop: '',
    bottabData: app.globalData.bottabDataForPpsj,
    loadSuccess: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showLoading()
    this.setData({
      isShop: wx.getStorageSync("isShop"),
      ['bottabData[3].current']: true,
      userInfo: JSON.parse(wx.getStorageSync('userInfo'))
    })
  },
  switchBotab(e) {
    let isShop = wx.getStorageSync("isShop");
    let isOut = wx.getStorageSync("isOut"); 
    if (isShop == 1 && e.currentTarget.dataset.value == '入驻') {
      if (isOut == 1) {
        wx.showModal({
          title: '提示',
          content: '您的店铺已到期，请续费',
          showCancel: false,
          success: function (res) {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/shopIndex/shopIndex?whole=1'
              })
            }
          }
        })
      }
      else {
        wx.navigateTo({
          url: '/pages/sjwppublish/sjwppublish'
        })
      }
    }
    else if (isShop == 2 && e.currentTarget.dataset.value == '入驻') { }
    else {
      wx.navigateTo({
        url: e.currentTarget.dataset.url
      })
    }
  },
  // 查询购物车信息
  getCartInfo: function(){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shoppingCart/all',
      data: {
        userId: this.data.userInfo.id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        _this.setData({
          loadSuccess: true
        })
        wx.hideLoading()
        var obj={};
        for (var i = 0; i < res.data.data.length; i++) {
          var id = res.data.data[i].shopInfo.id;
          if(id){
            if (obj[id]) {
              res.data.data[i].checked = false;
              res.data.data[i].shopThing.realThingShowImg = res.data.data[i].shopThing.realThingShowImg.split(",");
              obj[id].push(res.data.data[i]);
            } else {
              obj[id] = [];
              res.data.data[i].checked = false;
              res.data.data[i].shopThing.realThingShowImg = res.data.data[i].shopThing.realThingShowImg.split(",");
              obj[id].push(res.data.data[i])
            }
          }
        } 
        var arr = [];
        for(var key in obj){
          let obj1 = {};
          obj1.checked = false;
          obj1.shopId = key;
          obj1.wareList = obj[key];
          arr.push(obj1);
        }
        _this.setData({
          cartData: arr
        })
      }
    })
  },
  // 全选
  allSelect: function (e) {
    var that = this;
    that.data.tatalPrice = 0;
      this.data.cartData.forEach(function (ele) {
        if (!that.data.allSelect) {
          ele.checked=true;
        }else{
          ele.checked = false;
        }
        ele.wareList.forEach(function (item) {
          if (!that.data.allSelect) {
            item.checked = true;
          } else {
            item.checked = false;
          }
          that.data.tatalPrice = (that.data.tatalPrice *100) + (item.shopThing.price * item.amount*100);
          that.data.tatalPrice = that.data.tatalPrice / 100;
        })
      })
      if (!this.data.allSelect) {
        this.setData({
          cartData: that.data.cartData,
          tatalPrice: that.data.tatalPrice,
          allSelect: true
        })
      } else {
        this.setData({
          cartData: that.data.cartData,
          tatalPrice: 0,
          allSelect: false
        })
      }
  },
  checkWare:function(e){
    var index=e.currentTarget.dataset.value;
    var pindex = e.currentTarget.dataset.pvalue;
    var id = e.currentTarget.dataset.id;
    var that=this;
    // if (this.data.addrId != id && this.data.addrId != ''){
    //   wx.showToast({
    //     title: '不能多家结算',
    //     icon: 'none',
    //     duration: 2000
    //   })
    // }
    // else{
      if (pindex == undefined) {//选择该店铺下所有商品  
        if (this.data.cartData[index].checked) {

          this.data.cartData[index].checked = false;
          this.data.cartData[index].wareList.forEach(function (ele) {
            ele.checked = false;
            that.data.tatalPrice = (that.data.tatalPrice *100) - (ele.shopThing.price * ele.amount * 100);
            that.data.tatalPrice = that.data.tatalPrice /100;
          })
        } else {
          this.data.cartData[index].checked = true;
          this.data.cartData[index].wareList.forEach(function (ele) {
            ele.checked = true;
            that.data.tatalPrice = (that.data.tatalPrice * 100) + (ele.shopThing.price * ele.amount * 100);
            that.data.tatalPrice = that.data.tatalPrice / 100;
          })
        }
      } else {//选择单个商品
        var item = this.data.cartData[pindex].wareList[index];
        if (this.data.cartData[pindex].wareList[index].checked) {
          this.data.cartData[pindex].wareList[index].checked = false;
          this.data.tatalPrice = (this.data.tatalPrice*100) - (item.shopThing.price * item.amount*100);
          that.data.tatalPrice = that.data.tatalPrice / 100;
        } else {
          this.data.cartData[pindex].wareList[index].checked = true;
          this.data.tatalPrice = (this.data.tatalPrice*100) + (item.shopThing.price * item.amount*100);
          that.data.tatalPrice = that.data.tatalPrice / 100;
        }
        var flag = true;
        this.data.cartData[pindex].wareList.forEach(function (ele) {
          if (ele.checked == false) {
            flag = false;
          }
        })
        this.data.cartData[pindex].checked = flag;
      }
      this.data.addrId = id;
      this.setData({
        addrId: this.data.addrId,
        tatalPrice: that.data.tatalPrice,
        cartData: this.data.cartData
      })
    // }
  },
  // 改变购买数量
  changeBuyNum:function(e){
    var index = e.currentTarget.dataset.value;
    var pindex = e.currentTarget.dataset.pvalue;
    var item = this.data.cartData[pindex].wareList[index];
    var money = this.data.tatalPrice;
    var type = e.currentTarget.dataset.type;
    if (type == "true") {//减少购买数量
      if (item.amount>1){
        item.amount--;
      }
    } else {// 增加购买数量
      item.amount++;
    }
    if (item.checked == true) {
      money = item.amount * item.shopThing.price;
    }
    this.setData({
      cartData:this.data.cartData,
      tatalPrice: money
    })
  },
  //删除商品
  delWare:function(e) {
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shoppingCart/del',
      data: {
        id: e.currentTarget.dataset.id
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if(res.data.success){
          var index = e.currentTarget.dataset.value;
          var pindex = e.currentTarget.dataset.pvalue;

          if (_this.data.cartData[pindex].wareList.length <= 1) {
            _this.data.cartData.splice(pindex, 1);
          } else {
            _this.data.cartData[pindex].wareList.splice(index, 1);
          }
          _this.setData({
            cartData: _this.data.cartData
          })
        }
        else{
          wx.showToast({
            title: res.data.error,
            icon: 'none',
            duration: 2000
          })
        }
      }
    })  
  },
  //结算
  balance:function(e){
    var total = 0,
        arrList = [];
    for(var i = 0; i < this.data.cartData.length; i++){
      var shopMoney = 0,
          arr = [],
          amount = 0;
      for(var j =0 ; j < this.data.cartData[i].wareList.length; j++){
        if(this.data.cartData[i].wareList[j].checked){
          let item = this.data.cartData[i].wareList[j]; 
          item.realThingShowImg = item.shopThing.realThingShowImg;
          item.thingName = item.shopThing.thingName;
          item.price = item.shopThing.price; 
          item.thingFare = item.shopThing.thingFare;
          arr.push(item);
          shopMoney += (item.shopThing.price * item.amount);
          amount += item.amount;
          
        }
      }
      var obj = {};
      obj.shopId = this.data.cartData[i].shopId;
      obj.shopMoney = shopMoney + this.data.cartData[i].wareList[0].shopThing.thingFare;
      obj.amount = amount;
      obj.wareList = arr;
      arrList.push(obj)
    } 
    if (obj == ''){
      wx.showToast({
        title: '您还没有选择商品',
        duration: 2000
      })  
    }
    else{
      for (var k = 0; k < arrList.length; k++){
        total += (arrList[k].shopMoney*100);
      }
      console.info(total/100)
      wx.navigateTo({
        url: '/pages/confirmOrder/confirmOrder?arr=' + JSON.stringify(arrList)+'&totalMoney='+(total/100),
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getCartInfo()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})